package com.chainyoung.component_tmperson.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.appcommon.hdwallet.CoinConstant;
import com.chainyoung.common.appcommon.hdwallet.OwnWalletUtils;
import com.chainyoung.common.appcommon.hdwallet.WordsListUtil;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.view.kprogresshud.KProgressHUD;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonFragmentComponent;
import com.chainyoung.component_tmperson.di.module.PersonFragmentModule;
import com.chainyoung.component_tmperson.ui.mvp.contract.ImportWalletContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.ImportWalletPresenter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

import static com.chainyoung.common.appcommon.hdwallet.CoinConstant.ETH;

public class ImportWalletByMnemonicFragment extends BaseFragment<ImportWalletPresenter> implements ImportWalletContract.View {

    @BindViews({R2.id.tv_index1, R2.id.tv_index2, R2.id.tv_index3, R2.id.tv_index4, R2.id.tv_index5, R2.id.tv_index6, R2.id.tv_index7, R2.id.tv_index8,
            R2.id.tv_index9, R2.id.tv_index10, R2.id.tv_index11, R2.id.tv_index12})
    List<TextView> textIndexs;

    @BindViews({R2.id.et_word1, R2.id.et_word2, R2.id.et_word3, R2.id.et_word4, R2.id.et_word5, R2.id.et_word6, R2.id.et_word7, R2.id.et_word8,
            R2.id.et_word9, R2.id.et_word10, R2.id.et_word11, R2.id.et_word12})
    List<EditText> editWordList;


    private String coinType = CoinConstant.ETH;//币种
    private List<String> wordsList = new ArrayList<>();

    private HdWalletCache hdWallet;


    public static ImportWalletByMnemonicFragment newInstance(String type) {
        ImportWalletByMnemonicFragment fragment = new ImportWalletByMnemonicFragment();
        Bundle args = new Bundle();
        args.putString("coinType", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            coinType = getArguments().getString("coinType");
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPersonFragmentComponent.builder()
                .appComponent(appComponent)
                .personFragmentModule(new PersonFragmentModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUi() {
        super.initUi();
        initIndexs();
        editWordList.get(0).clearFocus();
        setListeners();
    }


    private void initIndexs() {
        for (int i = 0; i < textIndexs.size(); i++) {
            textIndexs.get(i).setText(i + 1 + "");
        }
    }

    private void setListeners() {
        for (final EditText editText : editWordList) {
            editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (!WordsListUtil.wordIsValid(s.toString().trim())) {
                        editText.setTextColor(ContextCompat.getColor(mContext, R.color._F95A54));
                    } else {
                        editText.setTextColor(ContextCompat.getColor(mContext, R.color._061c69));
                    }
                }
            });
        }
    }

    public void restoreView(List<String> words) {
        for (int i = 0; i < words.size(); i++) {
            editWordList.get(i).setText(words.get(i));
        }
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void onFirstUserVisible() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_import_hdwallet_by_mnenomic;
    }

    @OnClick(R2.id.tv_save)
    void importWallet() {
        wordsList.clear();
        for (int i = 0; i < editWordList.size(); i++) {
            if (!TextUtils.isEmpty(editWordList.get(i).getText().toString().trim())) {
                wordsList.add(editWordList.get(i).getText().toString().trim());
            }
        }
        if (wordsList.size() < 12) {
            ToastUtil.showToast("请输入完整的助记词");
            return;
        }

        for (String word : wordsList) {
            if (!WordsListUtil.wordIsValid(word)) {
                ToastUtil.showToast("请输入正确助记词");
                return;
            }
        }

        hdWallet = OwnWalletUtils.importByMnemonic(mContext, SPUtil.getString(LibConstant.PIN_CODE), StringUtil.listToStringBySpace(wordsList), coinType);
        mPresenter.getAllHdWalletCaches(coinType);

    }


    @Override
    public void onAddHdWalletCacheSuccess(HdWalletCache data) {

        RouterUtils.getInstance()
                .build(RouterConstants.PATH_MAIN_MARKET_ACTIVITY)
                .withInt("page", 3)
                .withBoolean("isGetWallet", true)
                .navigation(mContext);

    }

    @Override
    public void onGetAllHdWalletCaches(List<HdWalletCache> datas) {
        if (datas != null) {
            for (HdWalletCache hdWalletCache : datas) {
                if (hdWalletCache.getAddress().equals(hdWallet.getAddress())) {
                    KProgressHUD.create(mContext)
                            .setCustomView(mContext, R.drawable.tips_error)
                            .setLabel(getString(R.string.tmperson_wallet_exsits))
                            .show().setDuration(1500);
                    return;
                }
            }
        }

        // 给新增钱包取名
        int num = datas == null ? 1 : datas.size()+1;
        hdWallet.setWalletName(hdWallet.getCoinType() + "-" + num);
        mPresenter.addHdWalletCache(hdWallet);
    }
}
